import { SearchEngineInterface,SearchResult } from "../engine";

import got  from "got";
import { JSDOM } from "jsdom";
import { Readability } from "@mozilla/readability";

import  puppeteer from "puppeteer";

class BingSearchEngine implements SearchEngineInterface {
  async search(query: string): Promise<SearchResult[]> {
    const result: SearchResult[] = [];
    
    const browser = await puppeteer.launch({ headless: true});
    
    const page = await browser.newPage();
  
    try {
      await page.evaluateOnNewDocument(() => {
        Object.defineProperty(navigator, 'webdriver', {
          get: () => false,
        });
      });
      await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3477.0 Safari/537.36");
          
      await page.goto('https://cn.bing.com', { waitUntil: 'networkidle2' });
      await page.type('input[name="q"]', query, { delay: 100 }); // 使用参数传入的query
      await page.keyboard.press('Enter');
      await page.waitForNavigation({ waitUntil: 'networkidle2' });
  
      const links: SearchResult[] = await page.evaluate(() => {

        const anchors = Array.from(document.querySelectorAll(".b_algo h2 a"));
        return anchors.map((a) => {
          const  s= new SearchResult( );
          s.content ="";
          s.title=a.textContent||"";
          s.url=a.getAttribute('href')||"";
          return s;
        });
      });
      console.log(links);
  
      result.push(...links); // 使用扩展运算符合并数组
  
    } catch (error) {
      console.error('执行过程中出现错误:', error);
    } finally {
      await browser.close();
    }


    for (let i = 0; i < result.length; i++) {
      try {
        const response = await got(result[i].url);
        const reader = new Readability(new JSDOM(response.body).window.document);
        const article = reader.parse();
        result[i].content = article.textContent;
      } catch (error) {
        console.log(error);
      }
    }
  
    return result; // 直接返回结果数组
  }
}

export {BingSearchEngine}